
var recorderManager = null;
import startRecord from 'dingtalk-jsapi/api/device/audio/startRecord';
import stopRecord from 'dingtalk-jsapi/api/device/audio/stopRecord';
import play from 'dingtalk-jsapi/api/device/audio/play';
import stop from 'dingtalk-jsapi/api/device/audio/stop';
import download from 'dingtalk-jsapi/api/device/audio/download';

import util from "/common/js/util.js";
import Qs from "qs";
/**
  {mediaId: "@lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA", remoteUrl: "https://static.dingtalk.com/media/lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA.ogg", duration: 2.46}
 */
const pageSize = 19;
var Timeout=null;

var time_obj={};//定时器对象集合

var app = getApp();
Page({
  data: {
    scrollTop: 0,
    toView: "",
    btnStatus:"stop",
    payIng:false,
    recorderManager:null,
    recordAudioArr:[

    ],// 音频文件数组
    mediaData:null,
    startTime:0,
    timeLength:"0:00",//显示录制时长
    residueTime:300,//倒计时 秒
    residueTimeLength:"4:59",//剩余录制时间
    queryData:{},
    map:new Map(),
    dataList: [],
    page: 1,
    pageSize: pageSize,
    showLoadMore: false,
    showLoadMoreTxt: "over",
    totalResult: pageSize,
    view:false,//查看模式
    loginUserId:"",//当前登录人员id
    enableNative:false
  },
  onLoad(e) {
   console.log(e);
   let loginUserId=app.prototype.$userId;

   dd.getAuthCode({
    success: function (res) {
      console.log(res);
    }
  });

    this.setData({
      queryData:e,
      dataList:[],
      map:new Map(),
      recordAudioArr:[],
      loginUserId
    });
    let view=false;
    if(loginUserId==e.userId){
      view=false;
    }else{
      view=true;
    }
    this.setData({
      view
    });
  //  console.log("--app.prototype.$userId:",loginUserId);

  dd.getSystemInfo({
    success: (res) => {
      // res.platform;
      //console.log("--res.platform",res.platform);
      if(res.platform=="iOS"){
        this.setData({
          enableNative:true
        })
       }
    }
  })

  if(app.prototype.$userName=="刘庆峰"){
    this.setData({
      enableNative:true
    })
  }


    dd.setNavigationBar({
      title: `${e.userName}的读书笔记`,
      success: () => {},
      fail: () => {},
      complete: () => {},
    });
    this.initFn();
 // this.showIntegralIcon();
  },
  getIsLogin(){
    let api = "/user/info/getIsLogin", list = {  };
    app.$post(api, list).then(re => {
      try {
        if (re.code == 401) {
          app.authLoginFn().then(res=>{
           // console.log("--detail--res:",res);
            this.tableList();

          })
        }
        else {
          this.tableList();
        };
      } catch (error) {
      }
    }).catch(err => {
     
    });
  },
  format(seconds) {//秒转化为分钟格式
    let s=Math.trunc(seconds);
    let minInt=Math.floor(s / 60);
    let min = minInt >= 10 ? minInt : '0' + minInt;
    s -= 60 * min;
    let sec = s >= 10 ? s : '0' + s;
    return  min + ':' + sec;
  },
  resetFn(){
    //重置参数
    this.setData({
      timeLength:"0:00",
      startTime:0,
      residueTimeLength:"4:59",
      residueTime:300
    })

  },

  initFn(){
    
    this.getIsLogin();
  },
  tableList(obj){
    let api = "/user/book/userNoteList";
    let list = {
      page: this.data.page,
      pageSize: this.data.pageSize,
      bookId: this.data.queryData.bookId,
      userId: this.data.queryData.userId,
    //  chapter: this.data.queryData.value
    };
    if(obj){
      list=util.mergeObj(list,obj)
    }
    if(this.data.queryData.day){
    //  let time= this.data.queryData.createTime.split(" ")[0];
     list.day=this.data.queryData.day;
    }
    
    console.log("--list:",list);
    let that = this;
    this.setData({
      showLoadMoreTxt: "load"
    });
    
    // console.log(this.data.totalnum,this.data.totalResult);
    //debugger
    if (this.data.dataList.length >= this.data.totalResult&&this.data.totalResult!=0) {
      this.setData({
        showLoadMoreTxt: "over"
      })
      dd.stopPullDownRefresh();
      return false;
    }
    dd.showLoading({
        content: '数据加载中...',
      })
   let audioArr=this.data.recordAudioArr;
   let map=this.data.map;
    app.$post(api, list).then(res => {
      dd.stopPullDownRefresh()
     dd.hideLoading();
      if (res.code == 200) {
        let arr=res.data.list;
        let arr_list=audioArr.concat(arr);
        // console.log("---arr_list:",arr_list);
        for(let a=0;a<arr_list.length;a++){
          let item=arr[a];
          item.startTime=0;
          let time_arr=item.createTime.split(" ");
          item.time=time_arr[1];
          item.timeLength= this.format(item.duration);
          let i_arr= map.get(item.createTime);
          if(util.isEmpty(i_arr)){
            i_arr=[];
            i_arr.push(item);
            map.set(item.createTime,i_arr);
          }else{
            i_arr.push(item);
            map.set(item.createTime,i_arr);
          }
        }

        // console.log("--map");
        // console.log(map);
        
        let dataList=[];

        for (const [key, value] of map.entries()) {
         
          let json={
            ...value[0],
            list:value
          }

          dataList.push(json)
        }


        // console.log(dataList);

      //  let arr_list=dataList.concat(arr);
        // let page=this.data.page;
        // page=page+1;
        // console.log(JSON.stringify(arr_list[0]));
        this.setData({
          dataList,
          totalResult: res.data.totalResult,
          recordAudioArr: arr,
          showLoadMoreTxt: "over"
        });
        
      }else{
        util.message(res.message);

      }
    })
  },

  playFn(e){
    let arr = e.currentTarget.dataset.arr;
    let index= e.currentTarget.dataset.index;
    let parten= e.currentTarget.dataset.parten;
    let that=this;

    let id= e.currentTarget.dataset.id;
    let recordAudioArr=that.data.recordAudioArr
    // let list= recordAudioArr[parten].list;
    console.log(recordAudioArr);
    console.log(index);
    let item=recordAudioArr[index];
   console.log("--item:",item);
   

   let startTime=item.startTime;
   let duration=item.duration2;


   
//   console.log("list",list);

   

    download({
      mediaId: id,
      success: (suc) => {
        console.log("--suc",suc);
        if(!item.play){
          play({
            localAudioId: suc.localAudioId,
            success: (ms) => {
              // item.play=true;
              // item.startTime=0;

              // let startTime=item.startTime;
              // let duration=item.duration2;
              for (let a=0;a<recordAudioArr.length;a++) {
                let row= recordAudioArr[a];
                if(a==index){
                  row.play=true;
                  row.startTime=0;
                  row.duration2=row.duration;
                }else{
                  row.play=false;
                  row.timeLength=that.format(row.duration);
                }
             }
              // that.setData({
              //   [`recordAudioArr[${parten}].list`]:list
              // });
              // recordAudioArr
              that.setData({
                recordAudioArr
              });
              // let time_id=setInterval(() => {
              //   startTime= startTime+1 ;
              //   let timeLength=that.format(startTime);
              //   item.timeLength=timeLength;
              //   duration=duration-1;
              //   item.duration2=duration;
              //   that.setData({
              //     [`${arr}`]:list
              //   });

              //   if(duration==0){
              //     clearInterval(time_id)
              //   }
                
              // }, 1000);
              // time_obj[id]=time_id;
              // console.log("--time_id",time_obj);


            },
            fail: (e) => {
              console.log("--错误",e);
            },
            complete: () => {},
          });
        }else{
          stop({
            localAudioId: suc.localAudioId,
            success: (ms) => {

              for (let a=0;a<recordAudioArr.length;a++) {
                let row= recordAudioArr[a];
                row.play=false;
                row.timeLength=that.format(row.duration);
             }
              that.setData({
                recordAudioArr
              });

            },
            fail: (e) => {
              // console.log("--错误",e);
            },
            complete: () => {},
          })
        }
        

      },
      fail: () => {},
      complete: () => {},
    });
    
  },


  addNoteFn(obj){
    let api = "/user/book/addNote";
    let list = {
      ...this.data.queryData
    };
    list.chapter=this.data.queryData.value
    if(obj){
      list=util.mergeObj(list,obj)
    }
    console.log("--list:",list);
    let that = this;
    
    dd.showLoading({
        content: '数据提交中...',
      })
    app.$post(api, list).then(res => {
     dd.stopPullDownRefresh()
     dd.hideLoading();
      if (res.code == 200) {
        this.setData({
          "queryData.note":""
        })
        this.searchFn();
        this.showIntegralIcon(res.data);
        this.addReadLogFn();
      }else{
        util.message(res.message);

      }
    })
  },
  addReadLogFn(){
    let api = "/user/book/addReadLog";
    let list = {
      ...this.data.queryData
    };
    
    let that = this;
  
   
    app.$post(api, list).then(res => {
     
      if (res.code == 200) {
        
        
      }else{
        util.message(res.message);

      }
    })
  },
  onPullDownRefresh() {
    // 页面被下拉
    this.setData({
      showLoadMoreTxt: "load"
    });
    this.searchFn();
  },
  scroll(e){

  },
  searchFn(obj) {
    this.setData({
      page: 1,
      pageSize,
      recordAudioArr: []
    });
    this.tableList(obj)
  },
  onScrollToLower(){
   // console.log("---触底了!");
  //  this.tableList()
  },

  //开始录音
  startRecordFn(){
    this.setData({
      btnStatus:"start"
    })
    this.resetFn();
    // recorderManager.start({ duration: 60 });
    let that=this;  
    
    Timeout=setInterval(() => {
      let payIng=that.data.payIng;
      let startTime=that.data.startTime;
    //  let nowTime=new Date();

      startTime= startTime+1 ;
    //  console.log("----startTime",startTime);

      let timeLength=that.format(startTime);
    //  console.log("----timeLength",timeLength);

      let residueTime=that.data.residueTime;
      
      residueTime=residueTime-1;
      let residueTimeLength=that.format(residueTime);
      that.setData({
        payIng:!payIng,
        startTime,
        timeLength,
        residueTime,
        residueTimeLength
      });
      if(residueTime==0){
        console.log("--自动停止录音");
        that.stopRecordFn()
      }
      
    }, 1000);

    startRecord({
      maxDuration:300,
      success: (res) => {
        console.log("--开始录制res",res);
      //  res.play=false;
        this.setData({
          mediaData:res
        })
        
      },
      fail: () => {},
      complete: () => {},
    });
  },
  stopRecordFn(){
    this.setData({
      btnStatus:"stop"
    })
    // recorderManager.stop();

    clearTimeout(Timeout);
    this.setData({
      payIng:false
    })

    stopRecord({
      localAudioId:this.data.mediaData.mediaId,
      success: (res) => {
        console.log("--停止录制res",res);
        let duration=Math.round(res.duration);//4舍五入 等于300 则为5分钟
        res.roundDuration=duration;
        this.addNoteFn(res);
      //  console.log("--时长:",timeLength);
        // let recordAudioArr=this.data.recordAudioArr;
        // recordAudioArr.unshift(res);
        // this.setData({
        //   recordAudioArr
        // })
      },
      fail: () => {},
      complete: () => {},
    });
    
  },
  bindKeyInput(e) {
    let key = "queryData.note";
    // util.debounce(() => {
     
    // }, 300);
    this.setData({
      [`${key}`]: e,
    });
  },
  deleteFn(e){
    let index = e.currentTarget.dataset.index;

    dd.confirm({
      title: '温馨提示',
      content: '是否删除该录音文件?',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      success: (result) => {
        if (result.confirm) {
          this.delete(index);
        }
      },
    });
  },
  delete(index){
    let recordAudioArr=this.data.recordAudioArr;
    recordAudioArr.splice(index, 1);
    this.setData({
      recordAudioArr
    })
    
  },
  //打卡成功提示
  showIntegralIcon(data){
    let content="";
    if(data.fullMap.type==1){
      content+=`月全勤获得${data.fullMap.integral}积分\n`;
    }
    if(data.daysMap.type==1){
      content+=`连续打卡获得${data.daysMap.integral}积分\n`;
    }
    if(data.readMap.type==1){
      content+=`读书获得获得${data.readMap.integral}积分\n`;
    }
    if(content){
      dd.showModal({
        cells: [
          {
            //         https://img.alicdn.com/tfs/TB1KzrwRFXXXXasXXXXXXXXXXXX-540-380.png
            //        /static/img/dakachengong.png
            image:
              'https://img.alicdn.com/tfs/TB1KzrwRFXXXXasXXXXXXXXXXXX-540-380.png',
            title: '打卡成功,恭喜获得以下奖励:',
            content,
          }
          
        ],
        image: 'image示例值',
        title: 'title示例值',
        content: 'content示例值',
        buttonLabels: ['知道了'],
        success: (res) => {
          const { buttonIndex } = res;
        },
        fail: () => {},
        complete: () => {},
      });
    }

  },
  onShareAppMessage() {

    let p = Qs.stringify(this.data.queryData);
    let path = '/pages/note/noteGroup/noteGroup';
     let url = `${path}?${p}`;
    return {
      title: '恒丽书城',
      desc: `${this.data.queryData.userName}的读书笔记`,
      path: url,
    };
  },
});
